<?php
/*
 * @Description    : 邮件发送任务
 * @Version        : 1.0.0
 * @Author         : QianLong
 * @Date           : 2020-01-22 15:56:35
 * @LastEditors    : QianLong
 * @LastEditTime   : 2024-01-16 17:02:42
 */

declare(strict_types=1);

namespace App\Job;

use Hyperf\AsyncQueue\Job;
use App\Common\RedisCache;
use Symfony\Component\Mailer\Transport;
use Symfony\Component\Mailer\Mailer;
use Symfony\Component\Mime\Email;

class SendEmailJob extends Job
{
    public $params;

    public function __construct($params)
    {
        $this->params = $params;
    }

    public function handle()
    {
        if (!empty($this->params) && is_array($this->params)) {
            $redisCache = new RedisCache;
            $mail = new \EasySwoole\Smtp\Mailer(true);
            $serverInfo = $redisCache->getEmailServer($this->params['es_id']);
            $mail->setTimeout(5);
            $mail->setMaxPackage(1024 * 1024 * 5);
            $mail->setHost($serverInfo['smtp_server']);
            $mail->setPort((int)$serverInfo['port']);
            if ((int)$serverInfo['is_ssl'] == 1) {
                $mail->setSsl(true);
            }
            $mail->setUsername($serverInfo['smtp_username']);
            $mail->setPassword($serverInfo['smtp_password']);
            $mail->setFrom($serverInfo['sender'], $serverInfo['sender_name']);
            if (isset($this->params['reply_email'])) {
                $mail->setReplyTo($this->params['reply_email']);
            }
            $emailSetting = $redisCache->getEmailSetting($this->params['uid']);
            $emailArray = explode(',', $this->params['email']);
            $emailArray = array_flip(array_unique($emailArray));
            foreach ($emailArray as $email => $in) {
                $emailArray2 = explode('|',$email);
                $emailArray2[1] = isset($emailArray2[1])? $emailArray2[1]: '';
                if (!empty($this->params['filter_id'])) {
                    $result = $redisCache->setFilterEmail($this->params['uid'].':'.$this->params['filter_id'], $email);
                    if ($result) {
                        return $this->doSend($redisCache, $emailSetting, $emailArray2[0], $emailArray2[1], $mail);
                    }
                }else{
                    return $this->doSend($redisCache, $emailSetting, $emailArray2[0], $emailArray2[1], $mail);
                }
            }
            unset($email,$emailArray,$in,$redisCache,$emailSetting, $emailArray2);
        }
        return 'empty';
    }
    public function doSend($redisCache, $emailSetting, $email,$user_name,$mail)
    {
        if (empty($email)) {
            return false;
        }
        $day_limit = $redisCache->sendLimit($this->params['es_id'] . ':' . $email, 'day');
        if (!empty($day_limit) && !empty($emailSetting['day_limit']) && $day_limit > $emailSetting['day_limit']) {
            return false;
        }
        $hour_limit = $redisCache->sendLimit($this->params['es_id'] . ':' . $email, 'hour');
        if (!empty($hour_limit) && !empty($emailSetting['hour_limit']) && $hour_limit > $emailSetting['hour_limit']) {
            $redisCache->sendLimitDec($this->params['es_id'] . ':' . $email, 'day');
            return false;
        }
        $minute_limit = $redisCache->sendLimit($this->params['es_id'] . ':' . $email, 'minute');
        if (!empty($minute_limit) && !empty($emailSetting['minute_limit']) && $minute_limit > $emailSetting['minute_limit']) {
            $redisCache->sendLimitDec($this->params['es_id'] . ':' . $email, 'hour');
            $redisCache->sendLimitDec($this->params['es_id'] . ':' . $email, 'day');
            return false;
        }
        $title = (isset($this->params['title']) && !empty($this->params['title'])) ? $this->params['title'] : '邮件通知';
        if (isset($this->params['et_id']) && !empty($this->params['et_id'])) {
            $content = $redisCache->getEmailTemplateRealTime($this->params['et_id']);
            if (empty($content)) {
                $content = $this->params['content'];
            }
        } else {
            $content = $this->params['content'];
        }
        $content = htmlspecialchars_decode($content);
        $content = str_replace('#content#', $this->params['content'], $content);
        if (isset($user_name) && !empty($user_name)) {
            $content = str_replace('#user_name#', $user_name, $content);
        }
        foreach ($this->params as $key => $vo) {
            $keyArray = explode('-', $key);
            if (isset($keyArray[0]) && $keyArray[0] == 'ext') {
                $content = str_replace('#ext-' . $keyArray[1] . '#', $vo, $content);
            }
        }
        $postData['_id'] = createId('ESL');
        $send_result = false;
        $send_result_data = '';
        $send_error = '';
        try {
            $mail->addAddress($email);
            $text = new \EasySwoole\Smtp\Request\Html();
            $text->setSubject($title);
            $text->setBody($content . '<img src="https://21ds.cn/email/img?send_id=' . $postData['_id'] . '">');
            // 添加附件 可选
            if (isset($this->params['attachment'])) {
                $attachmentList = explode(',', $this->params['attachment']);
                foreach ($attachmentList as $url) {
                    $text->addAttachment($url);
                }
            }
            $send_result_data = $mail->send($text);
            $send_result = true;
        } catch (\EasySwoole\Smtp\Exception\Exception $exception) {
            $send_error = '('. $exception->getCode().') '.$exception->getMessage();
        }
        $postData['et_id'] = $this->params['et_id'];
        $postData['uid'] = $this->params['uid'];
        $postData['es_id'] = $this->params['es_id'];
        $postData['user_name'] = $user_name;
        $postData['content'] = $this->params['content'];
        $postData['send_content'] = $content;
        $postData['email'] = $email;
        $params = $this->params;
        unset($params['uid']);
        $postData['params'] = json_encode($params, JSON_UNESCAPED_UNICODE);
        unset($params);
        $postData['title'] = $title;
        $postData['send_result'] = $send_result;
        $postData['send_error'] = $send_error;
        $postData['send_result_data'] = $send_result_data;
        $postData['is_read'] = 0;
        $postData['read_time'] = 0;
        $postData['send_time'] = time();
        $postData['date'] = date('Ymd');
        $postData['hour'] = date('YmdH');
        $postData['only_hour'] = date('H') . ':00';
        $postData['hour_stamp'] = strtotime(date('Y-m-d H') . ':00:00');
        $postData['month'] = date('Ym');
        $postData['year'] = date('Y');
        $collection = mongodb2()->selectCollection('send_email_log_' . $this->params['uid']);
        // mongodb2()->send_email_log->insertOne($postData);
        $collection->insertOne($postData);
        (new \App\Service\Common)->mongodbIndexCreate($collection, 'uid_send_time', ['uid' => 1, 'send_time' => -1]);
        (new \App\Service\Common)->mongodbIndexCreate($collection, 'uid_send_time_es_id', ['uid' => 1, 'send_time' => -1, 'es_id' => -1]);
        unset($postData, $collection);
        return true;
    }
}
